package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import lombok.Setter;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Setter
    private RequestMappingHandlerMapping rmhp;

    @Override
    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Permission> list() {
        return permissionMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        //1.查询记录总数
        int count =  permissionMapper.query4Count(qo);
        if (count == 0) {
            return new PageResult(0,Collections.EMPTY_LIST);
        }
        List<Permission> list = permissionMapper.query4List(qo);
        //2.查询分页数据

        return new PageResult(count,list);
    }

    @Override
    public PageResult selectAllNames() {
        return permissionMapper.selectAllNames();
    }

    @Override
    public PageResult queryByRoleId(Long roleId) {
        return permissionMapper.queryByRoleId(roleId);
    }

    @Override
    public void reload() {
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhp.getHandlerMethods();
        Collection<HandlerMethod> ms = handlerMethods.values();
        List<String> exps = permissionMapper.selectAllResource();
        for (HandlerMethod m : ms) {
            RequiresPermissions anno = m.getMethod().getAnnotation(RequiresPermissions.class);
            if (anno != null) {
                String[] exp = anno.value();
                String resource = exp[0];
                String name = exp[1];
                if (!exps.contains(exp)) {
                    Permission permission = new Permission();
                    permission.setName(name);
                    permission.setResources(resource);
                    permissionMapper.insert(permission);
                }
            }
        }
    }
}
